/*----------------------------------------------------------------------------------------------
 *
 * This file is XIU's property. It contains XIU's trade secret, proprietary and
 * confidential information.
 *
 * The information and code contained in this file is only for authorized XIU employees
 * to design, create, modify, or review.
 *
 * DO NOT DISTRIBUTE, DO NOT DUPLICATE OR TRANSMIT IN ANY FORM WITHOUT PROPER AUTHORIZATION.
 *
 * If you are not an intended recipient of this file, you must not copy, distribute, modify,
 * or take any action in reliance on it.
 *
 * If you have received this file in error, please immediately notify XIU and
 * permanently delete the original and any copy of any file and any printout thereof.
 * (c) www.xiusdk.cn
 *---------------------------------------------------------------------------------------------*/

#import "SettingsViewController.h"
#import "SliderTableViewCell.h"
#import <objc/runtime.h>
#import "SimpleDataPicker.h"

#define kSettingsTitle @"title"
#define kSettingsPropertyName @"propname"
#define kSettingsMaxValue @"maxvalue"
#define kSettingsMinValue @"minvalue"
#define kSettingsSwitch  @"switch"

@interface SettingsViewController ()<SimpleDataPickerDelegate, UITextFieldDelegate>
{
    NSArray* _settings;
    NSArray<NSString*>* _sessionPresents;
    NSArray* _sessionPresentNames;
    NSString* _currentsessionPresent;
    SimpleDataPicker* _picker;
}
@end

@implementation SettingsViewController

-(void)setCaptureSession:(AVCaptureSession *)captureSession
{
    if( captureSession == _captureSession)
        return;
    
    if( _captureSession != nil)
    {
        [_captureSession removeObserver:self forKeyPath:@"sessionPreset"];
    }
    _captureSession = captureSession;
    
    if( captureSession  != nil)
    {
        NSArray<NSString*>* sessionPresents= @[AVCaptureSessionPresetPhoto, AVCaptureSessionPresetHigh, AVCaptureSessionPresetMedium, AVCaptureSessionPresetLow, AVCaptureSessionPreset352x288, AVCaptureSessionPreset640x480, AVCaptureSessionPreset1280x720, AVCaptureSessionPreset1920x1080, AVCaptureSessionPresetiFrame960x540, AVCaptureSessionPresetiFrame1280x720];
        NSMutableArray<NSString*>* sessions = [NSMutableArray array];
        NSMutableArray* sessionNames=[NSMutableArray array];
        for( int i = 0; i < sessionPresents.count; i++)
        {
            if([captureSession canSetSessionPreset:sessionPresents[i]])
            {
                [sessions addObject:sessionPresents[i]];
                
                [sessionNames addObject:[sessionPresents[i] substringWithRange:NSMakeRange(strlen("AVCaptureSessionPreset"), sessionPresents[i].length-strlen("AVCaptureSessionPreset"))]];
            }
        }
        _sessionPresents = sessions;
        _sessionPresentNames = sessionNames;
        _currentsessionPresent = [captureSession.sessionPreset substringWithRange:NSMakeRange(strlen("AVCaptureSessionPreset"), captureSession.sessionPreset .length-strlen("AVCaptureSessionPreset"))];
        
        [_captureSession addObserver:self forKeyPath:@"sessionPreset" options:0 context:nil];
    }
    else
    {
        _sessionPresents = nil;
        _currentsessionPresent = nil;
    }
    
    if(self.isViewLoaded)
    {
        [self.tableView reloadData];
    }
}

-(void)dealloc
{
    if(_captureSession)
    {
        [_captureSession removeObserver:self forKeyPath:@"sessionPreset"];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    _settings = @[
//
//                  @{kSettingsTitle: @"磨皮", kSettingsPropertyName : @"beautyParam.intensity", kSettingsMaxValue:@(100)},
//                  @{kSettingsTitle: @"美白", kSettingsPropertyName : @"beautyParam.whitenIntensity", kSettingsMaxValue:@(100)},
//                  @{kSettingsTitle: @"滤镜", kSettingsPropertyName : @"landscapeParam.intensity", kSettingsMaxValue:@(100)},
//
////                  @{kSettingsTitle: @"大眼", kSettingsPropertyName : @"enhancementParam.brightnessIntensity", kSettingsMinValue:@(-100), kSettingsMaxValue:@(100)},
////                  @{kSettingsTitle: @"瘦脸", kSettingsPropertyName : @"enhancementParam.sharpnessIntensity", kSettingsMaxValue:@(100)},
////                  @{kSettingsTitle: @"饱和度", kSettingsPropertyName : @"enhancementParam.saturationIntensity", kSettingsMinValue:@(-100), kSettingsMaxValue:@(100)},
////                  @{kSettingsTitle: @"阴影", kSettingsPropertyName : @"enhancementParam.shadowsIntensity", kSettingsMinValue:@(-100), kSettingsMaxValue:@(100)},
////                  @{kSettingsTitle: @"高亮", kSettingsPropertyName : @"enhancementParam.highlightsIntensity", kSettingsMinValue:@(-100), kSettingsMaxValue:@(100)},
//
////                  @{kSettingsTitle: @"瘦身", kSettingsPropertyName : @"longLegParam.intensity", kSettingsMaxValue:@(100)},
////                  @{kSettingsTitle: @"帧率", kSettingsPropertyName :  @"runBenchmark", kSettingsSwitch:@YES},
//
//                  ];
}

-(void)reloadData
{
    NSMutableArray* settings = [NSMutableArray arrayWithCapacity:30];
    
    if( self.beautyParam )
    {
        [settings addObjectsFromArray:@[
                                        @{kSettingsTitle: @"磨皮", kSettingsPropertyName : @"beautyParam.intensity", kSettingsMaxValue:@(100)},
                                        @{kSettingsTitle: @"美白", kSettingsPropertyName : @"beautyParam.whitenIntensity", kSettingsMaxValue:@(100)},
                                        ]];
    }
    
    if( self.sharpenParam )
    {
        [settings addObject:@{kSettingsTitle: @"清晰", kSettingsPropertyName : @"sharpenParam.intensity", kSettingsMaxValue:@(100)}];
    }
    if( self.landscapeParam )
    {
        [settings addObject:@{kSettingsTitle: @"滤镜", kSettingsPropertyName : @"landscapeParam.intensity", kSettingsMaxValue:@(100)}];
    }
    
    if( self.slenderParam )
    {
        [settings addObjectsFromArray:@[
                        @{kSettingsTitle: @"瘦脸", kSettingsPropertyName : @"slenderParam.intensity", kSettingsMaxValue:@(100)},
                        @{kSettingsTitle: @"大眼", kSettingsPropertyName : @"slenderParam.eyeBigIntensity", kSettingsMaxValue:@(100)},
                          ]];
    }
    _settings = settings;
    [self.tableView reloadData];
}
    

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if( section == 0 )
    {
        return _settings.count;
    }
    else
    {
        return 1;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if( indexPath.section == 0 )
    {
        SliderTableViewCell* cell = nil;
        if( indexPath.row < _settings.count)
        {
            NSDictionary* setting = _settings[indexPath.row];
            NSString* propName = [setting objectForKey:kSettingsPropertyName];
            
            NSArray* propNameList = [propName componentsSeparatedByString:@"."];
            id obj = self;
            if( propNameList.count >= 2 )
            {
                for ( int i = 0; i < propNameList.count-1; i++) {
                    obj = [obj valueForKey:propNameList[i]];
                }
                propName = propNameList.lastObject;
            }
            BOOL boolean = [[setting objectForKey:kSettingsSwitch] boolValue];
            if(boolean)
            {
                cell = [tableView dequeueReusableCellWithIdentifier:@"cell_switch"];
                BOOL value = [[obj valueForKey:propName] boolValue];
                cell.switchButton.on =  value;
                [cell.switchButton addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
            }
            else
            {
                cell = [tableView dequeueReusableCellWithIdentifier:@"cell_slider"];
                cell.slider.maximumValue = [[setting objectForKey:kSettingsMaxValue] integerValue];
                cell.slider.minimumValue = [[setting objectForKey:kSettingsMinValue] integerValue];
                int value = [[obj valueForKey:propName] intValue];
                cell.slider.value = value;
                cell.valueLabel.text = [NSString stringWithFormat:@"%@", @((int)value)];
                [cell.slider addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
            }
            cell.titleLabel.text = [setting objectForKey:kSettingsTitle];
        }
        return cell;
    }
    else
    {
        SliderTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"options_cell"];
        cell.titleLabel.text = @"分辨率";
        cell.textField.text = _currentsessionPresent;
        cell.textField.delegate = self;
        return cell;
    }
}

-(void)setDeviceCell:(SliderTableViewCell*)cell value:(id)value
{
    if([value isKindOfClass:[NSNumber class]])
    {
        cell.valueLabel.text = [NSString stringWithFormat:@"%@", value];
    }
    else
    {
        //cell.valueLabel.text = [NSString stringWithFormat:@"%@", value];
    }
}

-(void)valueChanged:(UISlider*)slider
{
    CGPoint pt = [slider.superview convertPoint:slider.center toView:self.tableView];
    NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:pt];
    if( indexPath == nil)
        return;
    if( indexPath.row < _settings.count)
    {
        NSDictionary* setting = _settings[indexPath.row];
        NSString* propName = [setting objectForKey:kSettingsPropertyName];
        
        NSArray* propNameList = [propName componentsSeparatedByString:@"."];
        id obj = self;
        if( propNameList.count >= 2 )
        {
            for ( int i = 0; i < propNameList.count-1; i++) {
                obj = [obj valueForKey:propNameList[i]];
            }
            propName = propNameList.lastObject;
        }
        
        SliderTableViewCell* cell =  [self.tableView cellForRowAtIndexPath:indexPath];
        if( [slider isKindOfClass:[UISwitch class]])
        {
            UISwitch* switchButton = (UISwitch*)slider;
            [obj setValue:@(switchButton.on) forKey:propName];
        }
        else
        {
            if( cell )
            {
                cell.valueLabel.text = [NSString stringWithFormat:@"%@", @((int)slider.value)];
            }
            
            id first = [[propName substringToIndex:1] uppercaseString];
            id second = [propName substringFromIndex:1];
            SEL selector = NSSelectorFromString([NSString stringWithFormat:@"set%@%@:", first, second]);
            if([obj respondsToSelector:selector])
            {
                IMP imp = [obj methodForSelector:selector];
                typedef void (*ImpFunc)(id, SEL, id);
                ImpFunc func = (ImpFunc)imp;
                func(obj, selector, @((int)slider.value));
            }
            else
            {
                [obj setValue:@((int)slider.value) forKey:propName];
            }
        }
    }
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if( object == _captureSession && [@"sessionPreset" isEqualToString:keyPath])
    {
        _currentsessionPresent = [_captureSession.sessionPreset substringWithRange:NSMakeRange(strlen("AVCaptureSessionPreset"), _captureSession.sessionPreset .length-strlen("AVCaptureSessionPreset"))];
        SliderTableViewCell* cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
        if(cell)
        {
            cell.textField.text = _currentsessionPresent;
        }
    }
    else
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

-(void)simpleDataPicker:(SimpleDataPicker*)simpleDataPicker selectedIndex:(NSInteger)index data:(id)data
{
    simpleDataPicker.delegate = self;
    if( index>=0 && index < _sessionPresents.count)
    {
        if([_captureSession canSetSessionPreset:_sessionPresents[index]])
        {
            [_captureSession stopRunning];
            [_captureSession beginConfiguration];
            [_captureSession setSessionPreset:_sessionPresents[index]];
            [_captureSession commitConfiguration];
            [_captureSession startRunning];
        }
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    _picker.delegate = self;
    _picker = nil;
    
    _picker = [[SimpleDataPicker alloc] initWithList:_sessionPresentNames];
    _picker.defaultIndex = [_sessionPresentNames indexOfObject:_currentsessionPresent];
    _picker.delegate = self;
    [_picker presentWithAnimated:YES completion:nil];
    return NO;
}
@end
